package com.anrongtec.zcpt.base;

import java.util.List;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import android.content.Context;
import android.view.View;

public abstract class CommonSeletorAdapter<T> extends CommonAdapter<T> {
	private int selection = -1; // 当前选中item 下标
	private int defaultSelection = -1;// 默认第个Item是选中的
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder, int position) {
			setRadio(position);
		}

		@Override
		public boolean onItemLongClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder,
				int position) {
			return false;
		}
	};

	@Override
	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		try {
			throw new Exception("使用此方法会造成单选失效！！，单击效果请在selectItem处理");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public CommonSeletorAdapter(Context context, int layoutId, List<T> datas, int defaultSelection) {
		this(context, layoutId, datas);
		setDefaultSelection(defaultSelection);
	}

	public CommonSeletorAdapter(Context context, int layoutId, List<T> datas) {
		super(context, layoutId, datas);
		super.setOnItemClickListener(onItemClickListener);
	}

	public int getSelection() {
		return selection;
	}

	public void setSelection(int selection) {
		this.selection = selection;
	}

	public int getDefaultSelection() {
		return defaultSelection;
	}

	public void setDefaultSelection(int defaultSelection) {
		this.defaultSelection = defaultSelection;
		this.selection = defaultSelection;
	}

	public void setRadio(int position) {
		notifyItemChanged(getSelection());
		setSelection(position);
		notifyItemChanged(position);
	}

	@Override
	protected void convert(ViewHolder holder, T item, int position) {

		// 默认选择时的处理
		if (selection == position && position == defaultSelection) {
			selectItem(holder, item, position, true);
			return;
		}
		if (selection == position) {
			selectItem(holder, item, position, false);
		} else {
			convertItem(holder, item, position);
		}

	}

	public abstract void convertItem(ViewHolder holder, T item, int position);

	public abstract void selectItem(ViewHolder holder, T item, int selection, boolean isDefault);

}
